<template>

	<my-nav-bar bgType="transparent"></my-nav-bar>
	
	<view class="AvatarArea" :style="{ height: AvatarAreaHeight + 'px' }">
		<view class="bg"></view>
		<image class="AvatarImage" :src="displayUserInfo.avatarUrl" :style="{ top: AvatarImagePaddingTop + 'px' }"></image>
		<p class="WxNickName" :style="{ bottom: WxNicknameBottom + 'px' }" > {{displayUserInfo.name}} </p>
	</view>
	
	<view class="MyPage pageBg" :style="{ paddingTop: AvatarAreaHeight + 'px' }"> 
		
		<view class="UserInfoArea Module" >
			<view class="not-logged-in" v-if="!isLoggedIn">
				<p class="UserName text"> 请点击登录↓ </p>
			</view>
			<view class="logged-in" v-else>
				<p class="UserName text"> 尊敬的 {{displayUserInfo.name}} {{ displayUserInfo.gender ? ( displayUserInfo.gender=='male' ? "先生" : "女士" ) : ('')  }} : </p>
				<p class="welcome text"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;欢迎光临 七彩童年高端儿童摄影！ </p>
			</view>
	
			<uv-button class="loginButton" type="success" shape="circle" plain @click="onClickLogin"> {{isLoggedIn ? '退出登录' : '微信一键登录'}} </uv-button>
		</view>
		
		<view class="MyOperationArea Module">
			<view class="row">
				<view class="text"> 我的预约  [待开放] </view>
				<view class="arrow"> <uni-icons type="right" size="25" color="white"></uni-icons> </view>
			</view>
			<view class="row">
				<view class="text"> 我的留言  [待开放] </view>
				<view class="arrow"> <uni-icons type="right" size="25" color="white"></uni-icons> </view>
			</view>
			<view class="row" @click="toUrl('/pages/MyFavorList/MyFavorList')">
				<view class="text"> 我的样片收藏 </view>
				<view class="arrow"> <uni-icons type="right" size="25" color="white"></uni-icons> </view>
			</view>
			<view class="row">
				<view class="text"> More </view>
				<view class="arrow"> <uni-icons type="right" size="25" color="white"></uni-icons> </view>
			</view>
			<!-- <view class="row">
				<button @click="openPopup"> [debug]打开Popup </button>
			</view> -->
		</view>
		

	</view>
	
	<view :class="['Popup', isPopupFold ? 'fold' : '']" :style="{ height: PopupAreaHeight + 'px', bottom: PopupAreaTranslateY + 'px' }">
		<!-- <text>Popup</text> -->
		<button class="closePopupButton" @click="closePopup">关闭</button>
		
		<view class="phrase phrase1" :style="{ zIndex: isHide1 ? -1 : 1919999 }">
			<h2 :class="['text', 'bold', isHide1 ? 'hide' : '']"> 您好，新朋友！</h2>
			<p  :class="['text', isHide2 ? 'hide' : '']"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;欢迎来到七彩童年 高端婴幼儿摄影 </p>
			<p  :class="['text', isHide3 ? 'hide' : '']"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;让我带您完成注册 </p>
			<button :class="['getUserInfoButton', isHide4 ? 'hide' : '']" @click="onClick_getUserInfoButton"> 填写个人信息 </button>
		</view>
		
		 <!-- open-type="chooseAvatar" -->
		
		<view class="phrase phrase2">
			<h2 :class="['text', 'bold', isHide5 ? 'hide' : '']"> 填写个人信息 </h2>
			<p  :class="['text', isHide6 ? 'hide' : '']"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;为了后续方便预约和留言，请告诉我您贵姓名、手机号，并请上传您的头像 </p>
			<view :class="['row', isHide7 ? 'hide' : '']">
				<view class="key" > 姓名 </view>
				<input class="value" v-model="nameInput" type="nickname" @input="onNameInputWriting" />
			</view>
			<view :class="['row', isHide8 ? 'hide' : '']">
				<view class="key"> 手机号 </view>
				<input class="value" v-model="phoneInput" type="number" />
			</view>
			<view :class="['row', isHide9 ? 'hide' : '']">
				<view class="key"> 头像 </view>
				<button class="chooseAvatarButton" open-type="chooseAvatar" @chooseavatar="onClickChooseAvatar"> 获取头像 </button>
			</view>
			<button :class="['commitButton', isHide10 ? 'hide' : '']" @click="onClick_commitButton"> 提交 </button>
		</view>
	
	</view>
	
	<floating-window :class="['float', String(float_class_name)]" :PhaseIdx="FloatingWindowPhaseIdx">
		<view class="infoBox">
			<image class="AvatarImage" :src="displayUserInfo.avatarUrl"></image>
			<view class="row confirmHint">
				欢迎回来！
			</view>
			<!-- {{ selectedDateObj }} -->
			<view class="row">
				<view class="value">  尊敬的 </view>
				<view class="key"> {{ UserInfoFromServer.name }} </view>
			</view>
		</view>
	
	</floating-window>
	
	
	<my-nav class="down-nav" :y="Number(5)" :x="XRef"></my-nav>
</template>

<script setup>
	import { ref, nextTick, onMounted } from 'vue';
	import { SYSTEM_INFO, getStatusBarHeight, getTitleBarHeight, getNavBarHeight, getLeftIcon } from '@/utils/system.js';
	import { BASE_URL, request } from "@/utils/request.js";
	import { onLoad, onReady, onShow, onHide, onUnload, onPageScroll } from "@dcloudio/uni-app";
	import { startsWith } from "@/utils/string.js";
	import { toUrl } from "@/utils/page.js";
	
	const AvatarAreaHeight = ref( getNavBarHeight() + 200 );
	const AvatarImagePaddingTop = ref( 0.6 * (getNavBarHeight() + 200) - 50 );
	const PopupAreaHeight = ref( uni.getWindowInfo().screenHeight - 0.6*(getNavBarHeight() + 200) );
	const PopupAreaTranslateY = ref( -uni.getWindowInfo().screenHeight + 0.6*(getNavBarHeight() + 200) );
	const WxNicknameBottom = ref( 0.42 * (getNavBarHeight() + 200) );
	
	//------------------------
	const app = getApp();
	
	const WxCode = ref('UNKNOWN');
	const WxOpenId = ref('UNKNOWN');
	const WxSessionKey = ref('UNKNOWN');
	
	// const isLoggedIn = ref(Boolean(false));
	const isLoggedIn = app.globalData.isLoggedIn;
	const isNewUser = ref(Boolean(false));
	
	const UserInfoFromServer = app.globalData.UserInfoFromServer;
	const displayUserInfo = ref( {} );
	
	const float_class_name = ref('');
	
	const loadDisplayUserInfo = ()=>{
		console.log("loadDisplayUserInfo(): global var in app.vue: UserInfoFromServer ref var: "); console.log(UserInfoFromServer.value);
		displayUserInfo.value = UserInfoFromServer.value;
		if ( UserInfoFromServer.value.name != "请登录" )
			displayUserInfo.value['avatarUrl'] = BASE_URL + `wx/user/avatar_image/${displayUserInfo.value.open_id}`;
	}
	onLoad(()=>{
		loadDisplayUserInfo();
		console.log("on load(): displayUserInfo ref var: "); console.log(displayUserInfo.value);
	})
	
	const onClickLogin = () => {
		if ( isLoggedIn.value == false ){
			QuickLogin();
		} else {
			isLoggedIn.value = false;
			displayUserInfo.value.name = "请登录";
			displayUserInfo.value.avatarUrl = "../../static/defaultAvatar.jpg";
		}
	}
	
	const QuickLogin = async function() {
	    getWxCode()
	        .then(async () => {
	            return getOpenIdAndSessionKey(); // 确保返回 Promise
	        })
	        .then(async () => {
	            await nextTick(); // 确保 Vue 完成响应式更新
	            console.log("qwq, getOpenIdAndSessionKey()完事了以后， 在queryOpenidInServer()之前， 试着拿一下WxOpenId ref变量的值：", WxOpenId.value);
	            return queryOpenidInServer(); // 确保返回 Promise
	        })
			.then(async ()=>{
				return getUserInfo();
			})
	        .catch(error => {
	            console.error("发生错误:", error);
	        });
	}
	
	const getWxCode = function() {
	    return new Promise((resolve, reject) => {
	        wx.login({
	            success(res) {
	                if (res.code) {
	                    console.log("wx.login()成功！res: "); console.log(res);
	                    WxCode.value = res.code;
	                    resolve(res.code);
	                } else {
	                    console.log("wx.login()失败！errMsg:"); console.log(res.errMsg);
	                    reject(res.errMsg);
	                }
	            }
	        });
	    });
	}
	
	const getOpenIdAndSessionKey = function() {
	    return new Promise(async (resolve, reject) => {
	        try {
	            let res = await request({ 
					url: 'wx/code2session', 
					method: 'GET', 
					data: { WxCode: WxCode.value } ,
				});
	            console.log("getOpenIdAndSessionKey(): res = "); console.log(res);
	            WxOpenId.value = res.data.openid; // 使用 res.data.openid 而不是 res.openid
	            WxSessionKey.value = res.data.session_key; // 使用 res.data.session_key 而不是 res.session_key
	            resolve();
	        } catch (error) {
	            reject(error);
	        }
	    });
	}
	
	const queryOpenidInServer = function() {
	    return new Promise((resolve, reject) => {
	        console.log("qwq, in queryOpenidInServer(), path var in url: ", WxOpenId.value);
	        request({
	            url: `wx/user/${WxOpenId.value}`,
	            method: 'GET',
	        }).then(response => {
	            // 处理成功响应
	            console.log('queryOpenidInServer()成功: response:', response);
				if ( startsWith(response.data, '[openid not exist]') && response.statusCode===400 )
					isNewUser.value = true;
				else 
					isNewUser.value = false;
	            resolve(response);
	        }).catch(error => {
	            // 处理错误响应
	            console.error('queryOpenidInServer()错误: error:', error);
	            reject(error);
	        });
	    });
	}
	
	const getUserInfo = async function(){
		return new Promise(async (resolve, reject) => {
		    try {
				if ( isNewUser.value === true ){
					console.log("getUserInfo():  是新用户");
					openPopup();					
				} else {
					console.log("getUserInfo():  是老用户");
					float_class_name.value = "appear";
					setTimeout(()=>{
						float_class_name.value = "";
					},2222);
					request({ url: `wx/user/${WxOpenId.value}`, method: 'GET' })
						.then(res=>{
							UserInfoFromServer.value = res.data;
							console.log("UserInfoFromServer.value: "); console.log(UserInfoFromServer.value);
							displayUserInfo.value = res.data;
							displayUserInfo.value['avatarUrl'] = BASE_URL + `wx/user/avatar_image/${displayUserInfo.value.open_id}`;
							isLoggedIn.value = true;
							return res;
						});
				}
				
		        resolve();
		    } catch (error) {
		        reject(error);
		    }
		});
	}
	
	
	
	const isPopupFold = ref(Boolean(true));
	const isHide1 = ref(Boolean(true)); 
	const isHide2 = ref(Boolean(true));
	const isHide3 = ref(Boolean(true));
	const isHide4 = ref(Boolean(true));
	const isHide5 = ref(Boolean(true));
	const isHide6 = ref(Boolean(true));
	const isHide7 = ref(Boolean(true));
	const isHide8 = ref(Boolean(true));
	const isHide9 = ref(Boolean(true));
	const isHide10 = ref(Boolean(true));
	
	function executeInstructions(instructions, interval) {
	  let index = 0;
	  const intervalId = setInterval(() => {
	    if (index < instructions.length) {
	      instructions[index](); // 直接调用函数或方法，假设函数没有参数
	      index++;
	    } else {
	      clearInterval(intervalId);
	      console.log('所有指令执行完毕。');
	    }
	  }, interval);
	}
	
	
	const openPopup = () => {
	    nextTick(() => {
			isPopupFold.value = false;
			PopupAreaTranslateY.value = 0;
			
			// 假设 instructions 数组中的每个函数都接收一个参数
			const instructions = [
			  () => { isHide1.value = false },
			  () => { isHide2.value = false },
			  () => { isHide3.value = false },
			  () => { isHide4.value = false },
			];
			executeInstructions(instructions, 1000);
	    });
	}
	
	const closePopup = ()=>{
	    nextTick(() => {
			isPopupFold.value = true;
			PopupAreaTranslateY.value = -uni.getWindowInfo().screenHeight + 0.6*(getNavBarHeight() + 200);
	    });
	}
	
	const onClick_getUserInfoButton = ()=>{
		
		const instructions = [
		  () => { isHide1.value = true },
		  () => { isHide2.value = true },
		  () => { isHide3.value = true },
		  () => { isHide4.value = true },
		];
		executeInstructions(instructions, 225);
		
		const instructions2 = [
		  () => { isHide5.value = false },
		  () => { isHide6.value = false },
		  () => { isHide7.value = false },
		  () => { isHide8.value = false },
		  () => { isHide9.value = false },
		  () => { isHide10.value = false },
		];
		executeInstructions(instructions2, 1000);
	}
	
	const nameInput = ref(null);
	const phoneInput = ref(null);
	
	const onClickChooseAvatar = (e)=>{
		// console.log("onClickChooseAvatar(): e: "); console.log(e);
		console.log("onClickChooseAvatar(): e.detail: "); console.log(e.detail);
		displayUserInfo.value.avatarUrl = e.detail.avatarUrl;
	}
	
	const onNameInputWriting = (e)=>{
		console.log("onNameInputWriting(): e: "); console.log(e);
		displayUserInfo.value.name = e.detail.value;
	}
	
	const onClick_commitButton = async ()=>{
			console.log("onClick_commitButton()");
			
			uni.uploadFile({  
				url: BASE_URL + 'wx/user/upload', // 替换为你的服务器上传接口  
				//--------以下相当于表单--------------------
				filePath: displayUserInfo.value.avatarUrl,  name: 'file', // 与后端@RequestPart("file")对应的字段名  
				formData: {
					open_id: WxOpenId.value,
					name: nameInput.value,
					phone: phoneInput.value,
					wx_gender: '0'
				},
				//--------以上相当于表单----------------------
				success: (uploadFileRes) => {  
					const data = JSON.parse(uploadFileRes.data); // 解析服务器返回的数据  
					console.log('uni.uploadFile(): 上传成功：', data);  
					// 在这里处理上传成功后的逻辑，比如显示消息、更新UI等  
					request({ url: `wx/user/${WxOpenId.value}`, method: 'GET' })
						.then( res=>{
							console.log("上传完事了以后，再从服务器获取一遍用户数据" ); console.log(res);
							UserInfoFromServer.value = res.data;
							displayUserInfo.value = res.data;
							displayUserInfo.value['avatarUrl'] = BASE_URL + `wx/user/avatar_image/${displayUserInfo.value.open_id}`;
							isLoggedIn.value = true; closePopup();
						});
				},  
				fail: (error) => {  
					console.error('uni.uploadFile(): 上传失败：', error);  
					// 在这里处理上传失败后的逻辑，比如显示错误消息等  
				}  
			});  
			
	}
	


	const logOut = () => {
		var that = this
		uni.showModal({
			title: '确定要退出登录吗？',
			success: function(res) {
				if (res.confirm) { //确认退出
					uni.removeStorageSync('localtoken')
					uni.removeStorageSync('userId');
					uni.removeStorageSync('userInfo');
					this.info = {};
					//that.nickname = ''
					//that.headimgurl = ''

					//跳转到首页
					uni.reLaunch({
						url: '/pages/home/index'
					})

				} else if (res.cancel) { //取消退出
					// console.log('用户点击取消');
				}
			}
		});

	}
	
	// ---------------------------------------------
	const XRef = ref( Number(5) );
	
	onLoad((event) => {
		XRef.value = event.LastIdx ? Number(event.LastIdx) : 5;
	});
	
</script>

<style lang="scss" scoped>
	.bold{
		font-weight: bold;
	}
	
	.AvatarArea{
		// border: 1px solid red;
		// background-color: pink;
		z-index: 1919809;
		position: fixed;
		width: 100%;
		top: 0;
		.bg{
			width: 100%;
			height: 60%;
			// background: rgba(255,255,255,0.55);
			// backdrop-filter: blur(5.5px);
			// box-shadow: 2px 4px 8px rgba(0, 0, 0, 0.4); /* 水平偏移量 垂直偏移量 模糊半径 阴影颜色 */
			
			background: rgba(250, 150, 0, 0.5);
			backdrop-filter: blur(5px);
			box-shadow: 5px 5px 5px 2px rgba(0, 0, 0, 0.2); /* 水平偏移量 垂直偏移量 模糊半径 阴影颜色 */
		}
		.AvatarImage{
			z-index: 1919811;
			position: absolute;
			height: 100px;
			width: 100px;
			border-radius: 50px;
			left: 10%;
			box-shadow: 0 4px 8px rgba(0, 0, 0, 0.4); /* 水平偏移量 垂直偏移量 模糊半径 阴影颜色 */
		}
		
		.WxNickName{
			// border: 1px solid blue;
			// z-index: 1919811;
			position: absolute;
			left: calc(10% + 100px + 10px);
			font-weight: 1000;
			font-size: 21px;
			// color: white;
			color: black;
		}

	}
	
	.MyPage{
		// border: 2px solid black;
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100vw;
		height: 100%;
		
		// z-index: 1919811;
	}
	
	.Module{
		left: 0; right: 0; margin: auto;
		width: 90%;
		border-radius: 50rpx;
		padding: 50rpx;
		min-height: 100px;
		background-color: rgba(0,0,0,0.2);
		backdrop-filter: blur(10px);
		margin-bottom: 20px;
	}
	
	.UserInfoArea{
		// border: 1px solid red;
		
		display: flex;
		flex-direction: column;
		
		.UserName{
			// border: 1px solid red;
			font-weight: bold;
			font-size: 50rpx;
		}
		.text{
			margin-bottom: 5%;
		}
		.loginButton{
			margin-top: 5%;
		}
	}
	
	.MyOperationArea{
		display: flex;
		flex-direction: column;
		.row{
			// border: 1px solid red;
			padding: 10px 0 10px 0;
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
		.row:not(:first-of-type) {
		  border-top: 1px solid #fff; /* 设置白色的上边框 */ 
		}
	}
	
	.Popup.fold{
		// height: 0;
		
		// transform: translateY(0);
		transition: 1s;
	}
	
	.Popup{
		// border: 2px solid red;
		// z-index: 114514;
		position: fixed;
		// bottom: 0;
		left: 0;
		width: 750rpx;
		// border-radius: 30px 30px 0 0;
		overflow: hidden;
		padding: 100rpx 50rpx 100rpx 50rpx;
		box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.4); /* 水平偏移量 垂直偏移量 模糊半径 阴影颜色 */
		
		background-color: rgba(255,255,255,0.55);
		backdrop-filter: blur(5.5px);
		
		// transform: translateY(-500px);
		transition: 1s;
		
		.closePopupButton{
			z-index: 1919910;
			position: absolute;
			bottom: 0;
			right: 0;
			height: 50px;
			width: 50px;
			border-radius: 50px;
			background-color: red;
		}
		
		.phrase{
			// border: 2px solid blue;
			width: 100%;
			position: absolute;
			top: 10%;
			left: 0;
			padding: 50rpx;
			margin: 20px auto;

			.text {
				margin: 10px 0 10px 0;
				font-size: 35rpx;
			}
			
			.bold{
				font-size: 50rpx;
			}
			
			.getUserInfoButton{
				border-radius: 25px;
				height: 50px;
				width: 80%;
				border: 1px solid green;
				color: green;
			}
			
			.text, .getUserInfoButton{
				opacity: 1;
				transform: translateY(0);
				transition: 0.5s;
			}
			
			.hide{
				opacity: 0;
				transform: translateY(10px);
				transition: 0.5s;
			}

		}
		
		.phrase {
		  .row {
			border: 1px solid greenyellow;
		    margin-bottom: 20px;
			display: flex; flex-direction: row; align-items: center; justify-content: center;
			padding: 10px;
			
			.key {
				width: 20%;
				font-size: 20px;
				color: #555;
				margin-bottom: 10px;
			}
			
			.value {
				width: 80%;
				padding: 10px;
				border: 1px solid #555;
				border-radius: 5px;
				font-size: 14px;
			}
			
			.chooseAvatarButton{
				border: 1px solid #555;
				border-radius: 25px;
				background-color: rgba(0,0,0,0.5);
				height: 50px;
				width: 100%;
			}
		  }
		  
		  .commitButton{
		  	border-radius: 25px;
		  	height: 50px;
		  	width: 80%;
		  	border: 1px solid green;
		  	color: green;
		  }
		  
		  .text, .row, .commitButton{
		  	opacity: 1;
		  	transform: translateY(0);
		  	transition: 0.5s;
		  }
		  
		  .hide{
		  	opacity: 0;
		  	transform: translateY(10px);
		  	transition: 0.5s;
		  }
		  
		}


	}

	.float{
		z-index: -1;
		opacity: 0;
		position: fixed; top: 0; left: 0;
		height: 100%; width: 100%;
		transform: translateY(-1000px);
		transform: scale(0.5);
		
		transition: 0.5s ease-in-out;
		
		
		.infoBox{
			width: 100%; height: 100%;
			// border: 1px solid blue;
			width: 100%; padding: 20rpx;
			display: flex; flex-direction: column; justify-content: center; align-items: center;
			
			.AvatarImage{
				width: 200rpx;
				height: 200rpx;
				border-radius: 400%;
			}
			.row{
				display: flex; flex-direction: row;
				margin: 20rpx;
			}
			
			.row.confirmHint{
				font-weight: 800;
				font-size: 100rpx;
			}
			
			.row{
				font-size: 50rpx;
				.key{
					margin-left: 20rpx;
					font-weight: 800;
				}
				.value{
					margin-left: 10rpx;
					white-space: nowrap;
				}
				
			}
		}
			
	}
	
	.float.appear{
		z-index: 2929820;
		opacity: 1;
		transform: translateY(0px);
		transform: scale(1);
		
		transition: 0.5s ease-in-out;	
	}

	.down-nav {
		// border: 10px solid red;
		position: fixed;
		bottom: 20rpx;
	}
</style>